package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    //新增套餐及商品分类
    @PostMapping
    public R<String> save(@RequestBody Category category){
        try {
            categoryService.save(category);
        }catch (Exception ex){
            return R.error("添加失败");
        }
        return R.success("添加成功");
    }
    @GetMapping("/page")
    public R<Page> categoryPage(int page,int pageSize){
//        设置分页构造器
        Page<Category> pages = new Page<>(page, pageSize);
        //设置条件构造器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        //添加排序条件，根据sort进行排序
        lqw.orderByDesc(Category::getSort);
        Page<Category> page1 = categoryService.page(pages);
        return R.success(page1);
    }

    @DeleteMapping
    public R<String> deletedCategory(Long id){
        /*try {
            categoryService.removeById(id);
        }catch (Exception ex){
            return R.error("删除失败");
        }
        return R.success("删除成功");*/
        categoryService.remove(id);
        return R.success("分类信息删除成功");
    }
    @PutMapping
    public R<String> updateById(@RequestBody Category category){
        try {
            categoryService.updateById(category);
        }catch (Exception e){
            return R.error("修改失败");
        }
        return R.success("修改成功");
    }
    @GetMapping("/list")
    public R<List<Category>> getListType( Category category){
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(Category::getSort).orderByAsc(Category::getUpdateTime);
        lqw.eq(category.getType() != null,Category::getType,category.getType());
        List<Category> list = categoryService.list(lqw);
        return R.success(list);
    }

}
